package xy.come.juhenews;

import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;

import butterknife.BindView;
import xy.come.juhenews.Base.BaseActivity;
import xy.come.juhenews.Fragment.FindFragment;
import xy.come.juhenews.Fragment.HomeFragment;
import xy.come.juhenews.Fragment.MinFragment;
import xy.come.juhenews.Fragment.VideoFragment;
import xy.come.juhenews.Uitils.PermissionsUtilX;
import xy.come.juhenews.Uitils.SPUtils;
import xy.come.juhenews.Uitils.ToastUtilsX;

public class MainActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener,PermissionsUtilX.IPermissionsCallback {

    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar bottomNavigationBar;
    private long mExitTime;
    private HomeFragment homeFragment;
    private VideoFragment videoFragment;
    private FindFragment findFragment;
    private MinFragment minFragment;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private PermissionsUtilX permissionsUtil;


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        getPermission();
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC
                );
        bottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.icon_home, "首页").setActiveColorResource(R.color.red))
                .addItem(new BottomNavigationItem(R.mipmap.icon_video, "视频").setActiveColorResource(R.color.wheel_item_text_color_selected))
                .addItem(new BottomNavigationItem(R.mipmap.icon_find, "发现").setActiveColorResource(R.color.home_btn))
                .addItem(new BottomNavigationItem(R.mipmap.icon_min, "我的").setActiveColorResource(R.color.system_blue_color))
                .setFirstSelectedPosition(0)
                .initialise();
        setDefaultFragment();
        bottomNavigationBar.setTabSelectedListener(this);
    }


    private void setDefaultFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.layFrame, new HomeFragment());
        transaction.commitAllowingStateLoss();
    }

    private void getPermission() {
        permissionsUtil = PermissionsUtilX
                .with(this)
                .requestCode(0)
                .isDebug(true)
                .permissions(PermissionsUtilX.Permission.Location.ACCESS_COARSE_LOCATION)
                .request();
    }


    @Override
    protected void initData() {
        initLocation();
    }

    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        startLocation();
    }

    /**
     * 设置高德地图定位参数
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(5000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                SPUtils.put(MainActivity.this,SPUtils.CITY,location.getCity());
                SPUtils.put(MainActivity.this,SPUtils.CODE,location.getCityCode());
                SPUtils.put(MainActivity.this,SPUtils.PROVINCE,  location.getProvince());
            }
        }
    };

    private void startLocation() {
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }


    @Override
    public void onTabSelected(int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        switch (position) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                }
                transaction.replace(R.id.layFrame, homeFragment);
                break;
            case 1:
                if (videoFragment == null) {
                    videoFragment = new VideoFragment();
                }
                transaction.replace(R.id.layFrame, videoFragment);
                break;
            case 2:
                if (findFragment == null) {
                    findFragment = new FindFragment();
                }
                transaction.replace(R.id.layFrame, findFragment);
                break;
            case 3:
                if (minFragment == null) {
                    minFragment = new MinFragment();
                }
                transaction.replace(R.id.layFrame, minFragment);
                break;
            default:
                break;
        }
        transaction.commit();

    }

    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //需要调用onRequestPermissionsResult
        permissionsUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            DestroyAllActivity();
            System.exit(0);
        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, String... permission) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, String... permission) {
        //权限被拒绝
        ToastUtilsX.showLongToast(MainActivity.this,"权限被拒绝，请在设置页自行给与权限");
    }
}
